#include "UpdateChecker.h"
#include <qdebug.h>
#include <qsslsocket.h>
#include <QCoreApplication>
#include <QDir>
#include <QStandardPaths>
#include <QDebug>
#include <QProcess>

// 定义更新服务器配置
const QString VERSION_CHECK_URL = "https://gitee.com/zhang424358225/water-station-updates/raw/master/version.json";
const QString UPDATE_BASE_URL = "https://gitee.com/zhang424358225/water-station-updates/raw/master/";

UpdateChecker::UpdateChecker(QObject *parent)
    : QObject(parent)
    , m_manager(new QNetworkAccessManager(this))
    , m_isChecking(false)
    , m_isDownloading(false)
    , m_downloadProgress(0)
    , m_forceUpdate(false)
    , m_overwriteExisting(true)
{
}

UpdateChecker::~UpdateChecker()
{
    if (reply) {
        reply->abort();
        reply->deleteLater();
    }
}

void UpdateChecker::checkForUpdates()
{
    if (m_isChecking) {
        return;
    }

    m_isChecking = true;
    emit isCheckingChanged(m_isChecking);

    QNetworkRequest request;
    request.setUrl(QUrl(UPDATE_BASE_URL+ "version.json"));
    request.setAttribute(QNetworkRequest::RedirectPolicyAttribute, QNetworkRequest::NoLessSafeRedirectPolicy);

    reply = m_manager->get(request);
    
    if (!reply) {
        m_isChecking = false;
        emit isCheckingChanged(m_isChecking);
        emit updateError("创建网络请求失败");
        return;
    }

    connect(reply, &QNetworkReply::finished, this, &UpdateChecker::onCheckFinished);
    connect(reply, &QNetworkReply::errorOccurred, this, [this](QNetworkReply::NetworkError error) {
        m_isChecking = false;
        emit isCheckingChanged(m_isChecking);
        emit updateError("检查更新时发生错误: " + QString::number(error));
    });
}

void UpdateChecker::onCheckFinished()
{
    m_isChecking = false;
    emit isCheckingChanged(m_isChecking);

    if (reply->error() != QNetworkReply::NoError) {
        emit updateError("检查更新失败: " + reply->errorString());
        return;
    }

    QByteArray data = reply->readAll();
    QJsonDocument doc = QJsonDocument::fromJson(data);
    if (doc.isNull() || !doc.isObject()) {
        emit updateError("解析版本信息失败");
        return;
    }

    QJsonObject obj = doc.object();
    QString latestVersion = obj["version"].toString();
    QString releaseNotes = obj["releaseNotes"].toString();
    QString downloadUrl = obj["url"].toString();
    bool forceUpdate = obj["forceUpdate"].toBool();
    QString appName = obj["app"].toString();

    if (latestVersion.isEmpty() || appName.isEmpty()) {
        emit updateError("版本信息不完整");
        return;
    }

    m_latestVersion = latestVersion;
    m_releaseNotes = releaseNotes;
    m_forceUpdate = forceUpdate;
    m_updateUrl = downloadUrl + appName;
    m_downloadPath = QStandardPaths::writableLocation(QStandardPaths::DownloadLocation) + "/" + appName;

    emit latestVersionChanged(m_latestVersion);
    emit releaseNotesChanged(m_releaseNotes);
    emit forceUpdateChanged(m_forceUpdate);

    // 比较版本号
    if (latestVersion > currentVersion()) {
        emit updateAvailable(latestVersion);
    } else {
        emit noUpdateAvailable();
    }
}

void UpdateChecker::downloadUpdate()
{
    if (m_isDownloading) {
        return;
    }

    m_isDownloading = true;
    emit isDownloadingChanged(m_isDownloading);
    m_downloadProgress = 0;
    emit downloadProgressChanged(m_downloadProgress);

    // 创建update目录
    QString updateDir = QCoreApplication::applicationDirPath() + "/update";
    QDir dir;
    if (!dir.exists(updateDir)) {
        dir.mkpath(updateDir);
    }
    
    // 更新下载路径到update目录
    QString downloadPath = updateDir + "/" + QFileInfo(m_downloadPath).fileName();
    
    // 检查文件是否已存在
    if (QFile::exists(downloadPath)) {
        if (!m_overwriteExisting) {
            qDebug() << "文件已存在，跳过下载: " << downloadPath;
            m_isDownloading = false;
            emit isDownloadingChanged(m_isDownloading);
            emit updateFinished();
            // 直接启动更新程序
            QProcess::startDetached(downloadPath);
            QCoreApplication::quit();
            return;
        }
        QFile::remove(downloadPath);  // 删除已存在的文件
    }
    
    QNetworkRequest request;
    request.setUrl(QUrl(m_updateUrl));
    request.setAttribute(QNetworkRequest::RedirectPolicyAttribute, QNetworkRequest::NoLessSafeRedirectPolicy);

    reply = m_manager->get(request);
    
    if (!reply) {
        m_isDownloading = false;
        emit isDownloadingChanged(m_isDownloading);
        emit updateError("创建网络请求失败");
        return;
    }

    connect(reply, &QNetworkReply::downloadProgress, this, &UpdateChecker::onDownloadProgress);
    connect(reply, &QNetworkReply::finished, this, &UpdateChecker::onDownloadFinished);
    connect(reply, &QNetworkReply::errorOccurred, this, [this](QNetworkReply::NetworkError error) {
        m_isDownloading = false;
        emit isDownloadingChanged(m_isDownloading);
        emit updateError("下载更新时发生错误: " + QString::number(error));
    });
}

void UpdateChecker::onDownloadProgress(qint64 bytesReceived, qint64 bytesTotal)
{
    if (bytesTotal > 0) {
        m_downloadProgress = static_cast<int>((bytesReceived * 100) / bytesTotal);
        emit downloadProgressChanged(m_downloadProgress);
    }
}

void UpdateChecker::onDownloadFinished()
{
    m_isDownloading = false;
    emit isDownloadingChanged(m_isDownloading);

    if (reply->error() != QNetworkReply::NoError) {
        emit updateError("下载更新失败: " + reply->errorString());
        return;
    }

    // 创建update目录
    QString updateDir = QCoreApplication::applicationDirPath() + "/update";
    QDir dir;
    if (!dir.exists(updateDir)) {
        dir.mkpath(updateDir);
    }
    
    // 更新下载路径到update目录
    QString downloadPath = updateDir + "/" + QFileInfo(m_downloadPath).fileName();

    QFile file(downloadPath);
    if (!file.open(QIODevice::WriteOnly)) {
        emit updateError("无法创建更新文件");
        return;
    }

    file.write(reply->readAll());
    file.close();

    emit updateFinished();
    
    // 启动更新程序
    QProcess::startDetached(downloadPath);
    QCoreApplication::quit();
}

void UpdateChecker::cancelDownload()
{
    if (reply && m_isDownloading) {
        reply->abort();
        m_isDownloading = false;
        emit isDownloadingChanged(m_isDownloading);
    }
}